package opl.utilities;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.google.gson.Gson;

public class JSONHelper {
	
	public static Object Deserialize(String jsonString,Class<?> type)
	{
		Gson serializer=new Gson();
		return serializer.fromJson(jsonString, type);
	}
	
	public static String  Serialize(Object objToSerialize)
	{
		Gson serializer=new Gson();
		return serializer.toJson(objToSerialize);
	}
	@SuppressWarnings("unchecked")
	public static <T> List<T> DeserializeListFromResult(String jsonString,Class<T> type) throws Exception
	{
		List<T> lst=new ArrayList<T>();
		jsonString=("{\"Result\":"+jsonString+"}");
		JSONArray jsonArray=new JSONObject(jsonString).getJSONArray("Result");
		for (int i=0;i<jsonArray.length();i++) {
		JSONObject jObj=jsonArray.getJSONObject(i);
		lst.add((T) Deserialize(jObj.toString(), type));
		}
		
		return lst;
	}
	@SuppressWarnings("unchecked")
	public static <T> List<T> DeserializeList(String jsonString,Class<T> type) throws Exception
	{
		List<T> lst=new ArrayList<T>();
		//jsonString=("{\"Result\":"+jsonString+"}");
		//JSONArray jsonArray=new JSONObject(jsonString).getJSONArray("Result");
		JSONArray jsonArray=new JSONArray(jsonString);
		for (int i=0;i<jsonArray.length();i++) {
		JSONObject jObj=jsonArray.getJSONObject(i);
			String jsonObjString=jObj.toString();
			lst.add((T) Deserialize(jsonObjString, type));
		}
		
		return lst;
	}
}
